
#include "util/fs.hxx"
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <errno.h>
#include <dirent.h>


bool FsUtility::fileExists(const std::string& fname) {
   
    return access(fname.c_str(), F_OK) == 0;
}

bool FsUtility::isDir(const std::string& fname) {

    struct stat s; 
	if( stat(fname.c_str(),&s) == 0 && (s.st_mode & S_IFDIR ) ) return true;
	
    return false;
}

DbStatus FsUtility::getChildren(const std::string& dir,
							std::vector<std::string>& result) {

    DbStatus ret;

    result.clear();
    DIR* d = opendir(dir.c_str());
    if (d == NULL) {
        return DbStatus(dir, errno);
    }

    struct dirent* entry;
    while ((entry = readdir(d)) != NULL) {

        if(strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) continue;

        result.push_back(entry->d_name);
    }

    closedir(d);

    return ret;
}

DbStatus FsUtility::deleteFile(const std::string& fname) {
   
    DbStatus ret;
    
    if (unlink(fname.c_str()) != 0) {

        ret = DbStatus(fname, errno);
    }

    return ret;
};

DbStatus FsUtility::createDir(const std::string& name) {
   
    DbStatus ret;
    
    if (mkdir(name.c_str(), 0755) != 0) {
        ret = DbStatus(name, errno);
    }

    return ret;
};

DbStatus FsUtility::deleteDir(const std::string& name) {
    
    DbStatus ret;
    
    if (rmdir(name.c_str()) != 0) {

        ret = DbStatus(name, errno);
    }

    return ret;
};

DbStatus FsUtility::getFileSize(const std::string& fname, uint64_t& size) {

    DbStatus ret;
    
    struct stat sbuf;
    if (stat(fname.c_str(), &sbuf) != 0) {
        size = 0;
        ret = DbStatus(fname, errno);
    } else {
        size = sbuf.st_size;
    }

    return ret;
}

DbStatus FsUtility::renameFile(const std::string& src, const std::string& target) {
   
    DbStatus ret;
    
    if (rename(src.c_str(), target.c_str()) != 0) {
        ret = DbStatus(src, errno);
    }
    
    return ret;
}


DbStatus FsUtility::truncateFile(const std::string& fname, uint64_t offset) {
   
    DbStatus ret;

    if(truncate(fname.c_str(), offset)) {
        ret = DbStatus(fname, errno);
    }
    return ret;
}

